package com.mys.maggie.redis.api.config;

import com.mys.maggie.redis.api.enums.RedisClientEnum;
import com.mys.maggie.redis.api.util.RedisHelpUtil;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * desc: redis分发
 * date:2020/9/24 15:50
 */
public class RedisDistributeService {

    /**
     * 加载redisTemplate实例
     * @param properties 配置文件
     * @return RedisTemplate
     */
    public static Map<String, RedisTemplate<String, Object>> getRedisTemplate(MagRedisProperties properties){
        Map<String, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>();
        Integer clientType = properties.getClientType();
        List<MagRedisProperties.Cluster> lettuceClusters = new ArrayList<>();
        List<MagRedisProperties.Cluster> jedisClusters = new ArrayList<>();
        List<MagRedisProperties.Cluster> standaloneClusters = new ArrayList<>();

        properties.getClusters().forEach(cluster -> {
            if ( cluster.getStandalone() ){ //单机只能是 jedis
                standaloneClusters.add( cluster );
                return;
            }
            //集群模式，分 jedis、lettuce两种。
            Integer innerClientType = RedisHelpUtil.swapIfPresentIsNull(cluster.getClientType(), clientType );
            if ( RedisClientEnum.REDIS_LETTUCE.getClientType().equals( innerClientType )){//jedis-cluster
                lettuceClusters.add( cluster );
            }else if ( RedisClientEnum.REDIS_JEDIS_CLUSTER.getClientType().equals( innerClientType ) ){
                jedisClusters.add( cluster );
            }
        });

        if (lettuceClusters.size() > 0){ //集群lettuce 始化
            Map<String, RedisTemplate<String, Object>> lettuceMap = LettuceConfigService.buildLettuceTemplateInstance(lettuceClusters,properties);
            redisTemplateMap.putAll(lettuceMap);
        }
        if (jedisClusters.size() > 0){ //集群jedis-cluster 始化
            Map<String, RedisTemplate<String, Object>> jedisClusterMap = JedisClusterConfigService.buildJedisTemplateInstance(jedisClusters,properties);
            redisTemplateMap.putAll(jedisClusterMap);
        }
        if (standaloneClusters.size() > 0){ //单机jedis 初始化
            Map<String, RedisTemplate<String, Object>> jedisAloneMap = JedisClusterConfigService.buildJedisAloneTemplateInstance(standaloneClusters,properties);
            redisTemplateMap.putAll( jedisAloneMap );
        }

        return redisTemplateMap;
    }


}
